<?php
/**
 * Created by PhpStorm.
 * User: wodrow
 * Date: 18-1-8
 * Time: 下午2:17
 */

namespace common\components\loan;

use common\models\LoanApply;
use yii\base\ErrorException;
use yii\helpers\ArrayHelper;
use yii\httpclient\Client;

/**
 * 易商平台接入融易行系统的API
 * 本文档定义的所有接口分为以下五种模式：网关接口、直连接口、异步通知、对账上传、对账下载
 * Class RongYiXing
 * @package common\components\loan
 */
class RongYiXing extends Loan implements Api
{
    const VERSION = 'v1.0.0';
    const NOTE = '腾邦-融易行系统的API';
    const COMPANY_CODE = 'ryx';

    /**
     * 借款企业申请借款
     * @param $requestNo 请求编号（调用方自定义，不可重复）
     * @param $orderId 订单编号，如浙B04-160111-004
     * @param $debtName 借款人姓名
     * @param $idCardNo 借款人身份证号码
     * @param $mobileNo 借款人手机号码
     * @param string $contract 借款合同号
     * @param $other_data  [$bankCardNo 银行卡号 $payAmount 购车总价 $downPayment 首付款 $requestTime 请求时间]
     */
    public function applyLoan()
    {
//        parent::checkHasLoanApplyErrorException($orderId);
        $other_data = unserialize($this->loan_apply->other_data);
        if (!isset($other_data['payAmount'])||!isset($other_data['downPayment'])||!isset($other_data['bankCardNo'])||!isset($other_data['debtAmount'])){
            throw new ErrorException("融易行申请借款需要other_data有bankCardNo,payAmount,downPayment,debtAmount");
        }else{
            $payAmount = $other_data['payAmount'];
            $downPayment = $other_data['downPayment'];
            $bankCardNo = $other_data['bankCardNo'];
            $debtAmount = $other_data['debtAmount'];
        }
        if (!isset($other_data['requestTime'])){
            $requestTime = date("YmdHis");
        }else{
            $requestTime = $other_data['requestTime'];
        }
        $requestTime = $requestTime - 60;
        $data = [
            'serviceName' => "DEBT_APPLY",
            'channel' => "YS",
            'userDevice' => "PC",
            'reqData' => [
                'requestNo' => $this->loan_apply->request_id,
                'orderId' => $this->loan_apply->order_id,
                'debtName' => $this->loan_apply->debt_name,
                'idCardNo' => $this->loan_apply->id_card_no,
                'mobileNo' => $this->loan_apply->mobile_no,
                'bankCardNo' => $bankCardNo,
                'payAmount' => $payAmount,
                'downPayment' => $downPayment,
                'requestTime' => $requestTime,
                'debtAmount' => $debtAmount,
                'contract' => $this->loan_apply->contract,
            ],
            'sign' => "",
            'version' => self::VERSION,
        ];
        $private_key = Config::$rong_yi_xing['private_key']; // 字符串
        $_req = json_encode($data['reqData']);
        openssl_sign($_req, $_signature, $private_key, "sha1WithRSAEncryption");
        $signature = base64_encode($_signature);
        $data['reqData'] = $_req;
        $data['sign'] = $signature;
        $client = new Client();
        $request = $client->createRequest()
            ->setMethod('post')
            ->setUrl(Config::$rong_yi_xing['url'])
            ->setHeaders([])
            ->setData($data);
        $response = $request->send();
        $r['my_post'] = $data;
        $x = json_decode($response->content, true);
        $r['original_back'] = $x;
        $public_key = Config::$rong_yi_xing['public_key'];
        $_sign= base64_decode($x['sign']);
        $x['sign_identify'] = openssl_verify($x['respData'], $_sign, $public_key, OPENSSL_ALGO_SHA1);
//        $x['sign_identify_error_str'] = openssl_error_string();
        $r['_back'] = $x;
        if ($x['sign_identify'] != 1){
            throw new ErrorException('从融易行获取的数据验签失败');
        }
        $x['respData'] = json_decode($x['respData']);
        $x['respData'] = ArrayHelper::toArray($x['respData']);
        if ($x['respData']['code']!=0){
            throw new ErrorException('从融易行获取的数据异常:'.$x['respData']['message']);
        }
        /*$loan_apply = new LoanApply();
        $loan_apply->request_id = $this->loan_apply->request_id;
        $loan_apply->order_id = $this->loan_apply->order_id;
        $loan_apply->debt_name = $this->loan_apply->debt_name;
        $loan_apply->id_card_no = $this->loan_apply->id_card_no;
        $loan_apply->mobile_no = $this->loan_apply->mobile_no;*/
        $this->loan_apply->created_at = $requestTime;
        $this->loan_apply->other_data = serialize($other_data);
        $this->loan_apply->apply_company = self::COMPANY_CODE;
        if ($this->loan_apply->save()){
            $r['loan_apply'] = $this->loan_apply->toArray();
        }else{
            throw new ErrorException("融易行-借款申请保存失败");
        }
        return $r;
    }
}